package cn.wolfcdoe.luowowo.comment.service.impl;

import cn.wolfcdoe.luowowo.comment.service.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    public static final int TRVEL_COMMENT_TYPE = 1;

    @Autowired
    private TravelCommentRepository repository;//crud

    @Autowired
    private MongoTemplate template;//高级查询
    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        //添加或更新
        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }
        //二级评论   如果是回复评论的话讲评论人的数据查出来
        if (comment.getType()==TRVEL_COMMENT_TYPE){
            //如果是二级评论,前端会船RefComment.id 过来
            if(StringUtils.hasLength(comment.getRefComment().getId())){
                comment.setRefComment(repository.findById(comment.getRefComment().getId()).get());
            }
        }
        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {

        //查询评论列表  自己封装pange
        Query query = new Query();
        //查询条件
        if(qo.getTravelId()!=-1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        Long count = template.count(query, TravelComment.class);
        //如果没有值就直接返回空
        if(count==0){
            return  Page.empty();
        }
        //分页查询
        Pageable page = PageRequest.of(qo.getCurrentPage() - 1,qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(page);
        //查询所有
        List<TravelComment> list = template.find(query, TravelComment.class);
        return new PageImpl(list,page,count);
    }

    @Override
    public Long getCount(Long travelId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        return template.count(query,TravelComment.class);
    }

    @Override
    public void commentDelete(String toid) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(toid));
        template.remove(query,TravelComment.class);
    }
}